package com.example.enjoyfood

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
import androidx.fragment.app.Fragment

class ProfileFragment : Fragment() {

    private lateinit var avatarImageView: ImageView
    private lateinit var nicknameEditText: EditText
    private lateinit var passwordEditText: EditText
    private lateinit var saveButton: Button
    private lateinit var logoutButton: Button

    private val sharedPreferences by lazy {
        requireActivity().getSharedPreferences("user_profile", Context.MODE_PRIVATE)
    }

    private val REQUEST_SELECT_AVATAR = 1

    @SuppressLint("MissingInflatedId")
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_profile, container, false)

        avatarImageView = view.findViewById(R.id.avatar_image_view)
        nicknameEditText = view.findViewById(R.id.nickname_edit_text)
        passwordEditText = view.findViewById(R.id.password_edit_text)
        saveButton = view.findViewById(R.id.save_button)
        logoutButton = view.findViewById(R.id.logout_button)
        // 加载保存的用户信息
        loadUserProfile()

        // 点击头像修改
        avatarImageView.setOnClickListener {
            selectAvatar()
        }

        // 保存按钮点击事件
        saveButton.setOnClickListener {
            saveUserProfile()
        }

        // 退出登录按钮点击事件
        logoutButton.setOnClickListener {
            logout()
        }

        return view
    }

    private fun loadUserProfile() {
        try {
            val nickname = sharedPreferences.getString("nickname", "未设置") ?: "未设置"
            val password = sharedPreferences.getString("password", "") ?: ""
            val avatarResId = sharedPreferences.getInt("avatar_res_id", R.drawable.default_avatar)

            nicknameEditText.setText(nickname)
            passwordEditText.setText(password)
            avatarImageView.setImageResource(avatarResId)
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(requireContext(), "加载用户信息失败", Toast.LENGTH_SHORT).show()
        }
    }

    private fun saveUserProfile() {
        val nickname = nicknameEditText.text.toString().trim()
        val password = passwordEditText.text.toString().trim()

        if (nickname.isEmpty() || password.isEmpty()) {
            Toast.makeText(requireContext(), "昵称和密码不能为空", Toast.LENGTH_SHORT).show()
            return
        }

        try {
            with(sharedPreferences.edit()) {
                putString("nickname", nickname)
                putString("password", password)
                apply()
            }
            Toast.makeText(requireContext(), "修改已保存", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(requireContext(), "保存用户信息失败", Toast.LENGTH_SHORT).show()
        }
    }

    private fun selectAvatar() {
        val intent = Intent(requireContext(), AvatarSelectionActivity::class.java)
        startActivityForResult(intent, REQUEST_SELECT_AVATAR)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_SELECT_AVATAR && resultCode == Activity.RESULT_OK) {
            val avatarResId = data?.getIntExtra("avatar_res_id", R.drawable.default_avatar)
                ?: R.drawable.default_avatar
            avatarImageView.setImageResource(avatarResId)

            // 保存选中的头像资源ID
            sharedPreferences.edit().putInt("avatar_res_id", avatarResId).apply()
        }
    }

    private fun logout() {
        // 清除登录状态
        val sharedPreferences =
            requireActivity().getSharedPreferences("app_prefs", Context.MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        editor.putBoolean("is_logged_in", false)
        editor.apply()

        // 跳转到登录界面
        val intent = Intent(requireContext(), LoginActivity::class.java)
        startActivity(intent)
        requireActivity().finish()
    }
}